import { useCallback, useEffect, useState, useMemo } from 'react';
import { Card, Input, Button, Space, Table, Modal } from "antd";
import { SearchOutlined } from '@ant-design/icons';
import {  deletePartitionInfo, addPartitionInfo, updatePartitionInfo } from "../api/partition";
import Message from '@/components/Message';
import PartitionForm from '../components/PartitionForm';
import { state as states } from "@/stores/Merchant"
import { useSnapshot } from 'valtio'
import { shop } from "../types/shop"

const Brand = () => {
    const state = useSnapshot(states)
    const [form, setForm] = useState<any>(
        {
            areaName: "",
            brandDesc: "",
            brandName: "",
            headName: "",
            phone: "",
            shopAddress: "",
        }
    );
    const [brandName, setBrandName] = useState("");
    const [modalShow, setModalShow] = useState(false);
    const [show, setShow] = useState(false);
    const [selectedBrand, setSelectedBrand] = useState<any>(null);

    const fetchBrandList = useCallback(() => {
        state.getData4({ brandName })

    }, [brandName]);
    const [modalShow2, setModalShow2] = useState(false);
    const [area, setArea] = useState("")
    const bindData = useMemo(() => {
        return state.shopList.filter((item: any) => item.areaName === area)
    }, [area])


    useEffect(() => {
        fetchBrandList();
    }, []);

    const handleSearch = () => {
        fetchBrandList();
    };

    // 查看店铺



    const handleAdd = () => {
        addPartitionInfo(form).then((res: any) => {
            if (res.code === 200) {
              
                fetchBrandList();
            }
        });
    };

    const handleUpdate = () => {
        updatePartitionInfo(form).then((res: any) => {
            if (res.code === 200) {
            
                fetchBrandList();
            }
        });
    };
    //  删除品牌
    const handleDelete = () => {
        deletePartitionInfo(selectedBrand).then((res: any) => {
            if (res.code === 200) {
                fetchBrandList();
            }
        });
    };

    const columns = [
        { title: "序号", dataIndex: 'key', key: 'key' },
        { title: "分区名称", dataIndex: 'areaName', key: 'areaName' },
        { title: "分区描述", dataIndex: 'brandDesc', key: 'brandDesc' },
        { title: "所属品牌", dataIndex: 'brandName', key: 'brandName' },
        { title: "分区负责人", dataIndex: 'headName', key: 'headName' },
        { title: "电话", dataIndex: 'phone', key: 'phone' },
        {
            title: "绑定店铺",
            render: (_: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => {
                        setArea(record.areaName)
                        setModalShow2(true)
                    }}>查看店铺</a>
                </Space>
            ),
        },
        {
            title: "员工账号",
            render: () => (
                <Space size="middle">
                    <a>查看账号</a>
                </Space>
            ),
        },

        {
            title: "操作",
            dataIndex: 'action',
            key: 'action',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => {
                        setForm(record);
                        setModalShow(true);
                    }}>编辑</a>
                    <a className='color-red' onClick={() => {
                        setSelectedBrand(record);
                        setShow(true);
                    }}>注销</a>
                </Space>
            ),
        }
    ];

    const info = {
        headTitle: "删除品牌确认",
        bodyTitle: `请确认是否删除品牌[${selectedBrand?.brandName}]！`,
        bodyContent: "如果删除，该品牌下的所有关联将自动解除~",
    };

    return (
        <div className='m=auto w-[100%] m-t-5'>

            <Message info={info} show={show} setShow={setShow} callBack={handleDelete} />
            <Card title='品牌筛选' className='m-auto w-[90%] rounded-none p-0'>
                <div style={{ display: "flex", height: "30px", lineHeight: '30px', padding: 0 }}>
                    <p className='m-0'>分区名称：</p>
                    <Input
                        value={brandName}
                        onChange={(e) => setBrandName(e.target.value)}
                        placeholder="请输入分区名称"
                        className='w-40 rounded-none m-l-2 m-r-10'
                    />
                    <Button
                        type="primary"
                        onClick={handleSearch}
                        className='rounded-none'
                        icon={<SearchOutlined />}
                    >
                        查询
                    </Button>
                </div>
            </Card>

            <Card className='w-[90%] m-auto mt-5 rounded-none'>
                <div className='flex justify-between items-center'>
                    <p>共有{state.areaList.length}条记录</p>

                    <Button
                        className='rounded-none'
                        type='primary'
                        onClick={() =>{ setModalShow(true)
                            setForm({
                                areaName: "",
                                brandDesc: "",
                                brandName: "",
                                headName: "",
                                phone: "",
                                shopAddress: "",
                            });
                        }

                        }
                    >
                        分区添加
                    </Button>
                </div>
                <Table
                    className='rounded-none'
                    columns={columns}
                    bordered
                    dataSource={state.areaList}
                    pagination={{
                        defaultPageSize: 5,
                        total: state.areaList.length,
                        showSizeChanger: true,
                        pageSizeOptions: ['5', '10', '20'],
                    }}
                />
            </Card>

            <Modal
                style={{ borderRadius: 0 }}
                title="分区管理"
                centered
                open={modalShow}
                footer={[
                    <Button key="back" onClick={() => {
                        setModalShow(false);
                        setForm({
                            areaName: "",
                            brandDesc: "",
                            brandName: "",
                            headName: "",
                            phone: "",
                            shopAddress: "",
                        });
                    }}>取消</Button>,
                    <Button key="submit" type="primary" onClick={() => {
                        setModalShow(false);
                        if (form._id) {
                            handleUpdate();
                        } else {
                            handleAdd();
                        }
                    }}>
                        确认
                    </Button>
                ]}
                onCancel={() => {
                    setModalShow(false);
                }}
            >
                <PartitionForm form={form} setForm={setForm} />
            </Modal>


            <Modal
                width={900}
                centered
                open={modalShow2}
                onOk={() => {
                    setModalShow2(false)
                }}
                onCancel={() => {
                    setModalShow2(false)

                }}
                footer={""}
            >
                <Table className='rounded-none m-t-10'
                    columns={shop}
                    dataSource={bindData}
                    bordered
                    pagination={{
                        defaultPageSize: 5, // 设置每页默认显示的行数
                        total: bindData.length,
                        showSizeChanger: true, // 不显示每页显示数量的选择器
                        showQuickJumper: false, // 不显示快速跳转到某一页的输入框
                        pageSizeOptions: ['5', '10', '20'],
                    }}
                />
            </Modal>

        </div>
    );
};

export default Brand;
